# leetcode 541 翻转字符串II

def reverse(string):
    s = list(string)
    left = 0
    right = len(s) - 1
    while left < right:
        s[left],s[right] = s[right], s[left]
        left += 1
        right -= 1
    return "".join(s)

class Solution:

    def reverseStr(self, s: str, k: int) -> str:
        n = len(s) // (2 * k)
        # s = list(s)
        result = ""
        for i in range(n):
            all = s[i * 2*k : (i + 1) * 2*k]
            pre = all[:len(all)//2]
            remain = all[len(all)//2:]
            result += (reverse(pre) + remain)

        remain_str = s[n * 2 * k:]
        if len(remain_str) < k:
            rs2 = reverse(remain_str)
            result += rs2
        elif k <= len(remain_str) < 2 * k:
            rs2 = reverse(remain_str[:k]) + "".join(remain_str[k:])
            result += rs2
        return result

